<?php

namespace control;
/*
*账户类
*/

class accountClass extends adIndexClass
{
    private const page = 'account';
    private const table = 'account';
    private const title = '银行账户';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => L('finance.table.zhbm'),
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => L('finance.table.zhmc'),
                        'width' => 250,
                    ],
                    'currency'         => [
                        'name'  => L('finance.table.bi_bie'),
                        'width' => 200,
                    ],
                    'subject'          => [
                        'name'  => L('finance.table.hui_ji_ke_mu'),
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => L('finance.table.balance') . "(" . static::$unit . ")",
                        'width' => 200,
                    ],
                    'initMoney'          => [
                        'name'  => L('finance.table.initMoney') . "(" . static::$unit . ")",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => L('finance.table.bei_zhu'),
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('finance.table.zhbm') => text(array("name" => "orderNo")),
                    L('finance.table.zhmc') => text(array("name" => "name")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{type:'现金'})\" class='spanButton'>" . L('finance.table.add') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del',type:'现金'})\">" . L('finance.table.shan_chu') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {

        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'type' => '现金',
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                'edit' => array("title" => L('finance.table.bian_ji'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'currency':
                        $currency = query('currency', "id = '$array[currencyId]'");
                        $row[] = $currency['name'];
                        break;
                    case 'subject':
                        $subject = query('subject', "id = '$array[subjectId]'");
                        $row[] = $subject['name'];
                        break;
                    case 'money':
                        $money = self::balance($array['id']);
                        $row[] = $money;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function bankOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('finance.table.zhbm') => text(array("name" => "orderNo")),
                    L('finance.table.zhmc') => text(array("name" => "name")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function bank()
    {
        $html = $this->bankOptions(false);
        //控件
        $button = "";
        if ($this->power('accountBank', "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{type:'银行存款'})\" class='spanButton'>" . L('finance.table.add') . "</span>\n";
        }
        if ($this->power('accountBank', "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del',type:'银行存款'})\">" . L('finance.table.shan_chu') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function bankSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'type' => '银行存款',
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("bankForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                'edit' => array("title" => L('finance.table.bian_ji'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'currency':
                        $currency = query('currency', "id = '$array[currencyId]'");
                        $row[] = $currency['name'];
                        break;
                    case 'subject':
                        $subject = query('subject', "id = '$array[subjectId]'");
                        $row[] = $subject['name'];
                        break;
                    case 'money':
                        $money = self::balance($array['id']);
                        $row[] = $money;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='bankForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    //余额
    public static function balance($accountId)
    {
        $account = query(self::table, "id = '$accountId'");
        $balance = find(array('table' => 'bookkeeping', 'single' => "accountId = '$accountId'", 'field' => "ifnull(sum(income-expenses),0) as money"))['money'];
        $balance += $account['initMoney'];
        return $balance;
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->post('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $currency = query('currency', "coid = '" . self::$coid . "' and isBase = '是'");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('finance.table.zhbm') . "：" => text(["name" => "orderNo", "value" => $info['orderNo']]),
                    must . L('finance.table.zhmc') . "：" => text(["name" => "name", "value" => $info['name']]),
                ],
                [
                    must . L('finance.table.bi_bie') . "：" => idSelect(array('sqlForm' => "currency where coid = '" . self::$coid . "' order by time asc", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'currencyId', 'title' => L('finance.table.qing_xuan_ze'), 'value' => $info['currencyId'] ?: $currency['id'])),
                    must . L('finance.table.hui_ji_ke_mu') . '：' => componentClass::subjectSelect($info['subjectId'])
                ],
                [
                    L('finance.table.initMoney') . "：" => text(["name" => "initMoney", 'unit' => static::$unit, "value" => $info['initMoney']]),
                ],
                [
                    L('finance.table.text') . "：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
            ], 'hidden' => hidden(array('name' => 'type', 'value' => $info['type'] ?: $this->post('type')))
        ]);
        //返回
        return $this->layer(array("title" => L('finance.table.bian_ji'), "height" => 350, "width" => 800, "html" => $html));
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'type' => $this->post('type'),
            'orderNo' => $this->post('orderNo'),
            'name' => $this->post('name'),
            'currencyId' => $this->post('currencyId'),
            'subjectId' => $this->post('subjectId'),
            'initMoney' => $this->post('initMoney'),
            'text' => $this->post('text')
        ];

        $annotation = [
            'type' => L('finance.table.zhlx'),
            'orderNo' => L('finance.table.zhbm'),
            'name' => L('finance.table.zhmc'),
            'currencyId' => L('finance.table.bi_bie'),
            'subjectId' => L('finance.table.hui_ji_ke_mu'),
        ];
        $rules = [
            'type' => 'required',
            'orderNo' => 'required',
            'name' => 'required',
            'currencyId' => 'required',
            'subjectId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit") && !$this->power('accountBank', "edit")) {
            $json['warn'] = L('finance.table.account_edit_permission');
        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and orderNo = '$field[orderNo]' and id !='$id'"))) {
            $json['warn'] = L('finance.table.yczcbmdzh');
        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and name = '$field[name]' and id !='$id'"))) {
            $json['warn'] = L('finance.table.yczcmcdzh');
        } elseif (empty($info['id']) && (!empty($field['initMoney']) && preg_match(checkPrice, $field['initMoney']) == 0)) {
            $json['warn'] = L('finance.table.csyegscw');
        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and subjectId = '$field[subjectId]' and id !='$id'"))) {
            $json['warn'] = L('finance.table.yzzhbdckm');
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'stid' => self::$stid,
                    'state' => '启用'
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            $record = query(self::table . '_record', "acid = '$id' and type = '初始余额'");
            if (empty($record['id']) && !empty($field['initMoney']) && $field['initMoney'] != 0) {
                $bool = self::record_ac($id, '收入', $field['initMoney'], L('finance.table.chu_shi_yu_e'), '初始余额');
                if ($bool !== true) {
                    $json['warn'] = $bool;
                } else {
                    self::tidyMoney($id, $field['initMoney']);
                }
            } elseif (!empty($record['id']) && empty($field['initMoney'])) {
                delete(array('table' => self::table . '_record', 'where' => "id = '$record[id]'"));
                self::tidyMoney($id, -$record['money']);
            } elseif (!empty($record['id']) && !empty($field['initMoney'])) {
                update(array('table' => self::table . '_record', 'field' => ['money' => $field['initMoney'], 'balance' => $field['initMoney']], 'where' => "id = '$record[id]'"));
                self::tidyMoney($id, $field['initMoney'] - $record['money']);
            }
            if (in_array($json['warn'], ['新增成功', '更新成功'])) {
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $id], L('finance.table.account_edit_text'));
                $this->logText(["type" => $field['type']=='现金'?self::page:'accountBank', "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }


    /**
     * 修改初始金额后要修改之后的记录
     * @param $acid
     * @param $money
     */
    public static function tidyMoney($acid, $money)
    {
        if (abs($money) > 0) {
            $all = find(array('table' => self::table . '_record', 'where' => "acid = '$acid' and type != '初始余额' order by id asc"));
            foreach ($all['array'] as $array) {
                update(array('table' => self::table . '_record', 'field' => ['balance' => $array['balance'] + $money], 'where' => "id = '$array[id]'"));
            }
        }
    }

    /**
     * 记录账户流水
     */
    public static function record_execute($data): bool|string
    {
        $data['acid'] = $data['acid'] ?? '';
        $data['direction'] = $data['direction'] ?? '';
        $data['money'] = $data['money'] ?? 0;
        $data['text'] = $data['text'] ?? '';
        $data['type'] = $data['type'] ?? '普通';
        $data['targetName'] = $data['targetName'] ?? '';
        $data['targetDate'] = $data['targetDate'] ?? '';
        $data['orderNo'] = $data['orderNo'] ?? '';
        $data['hiddenText'] = $data['hiddenText'] ?? '';
        if (empty($data['acid'])) {
            return L('finance.table.wzdjlzh');
        } elseif (empty($data['direction']) || !in_array($data['direction'], ['收入', '支出'])) {
            return L('finance.table.wzdsrzclx');
        } elseif (empty($data['money'])) {//|| preg_match(checkPrice, $data['money']) == 0
            return L('finance.table.wzdbdjehjegscw');
        } else {
            $data['money'] = $data['direction'] == '支出' ? (-$data['money']) : $data['money'];
            $warn = static::insert(array(
                'table' => self::table . '_record',
                'field' => array(
                    'coid' => self::$coid,
                    'acid' => $data['acid'],
                    'type' => $data['type'],
                    'direction' => $data['direction'] == '收入' ? 1 : 0,
                    'money' => $data['money'],
                    'balance' => self::money($data['acid']) + $data['money'],
                    'text' => $data['text'],
                    'targetName' => $data['targetName'],
                    'targetDate' => $data['targetDate'],
                    'orderNo' => $data['orderNo'],
                    'stName' => self::$user['name'],
                    'hiddenText' => $data['hiddenText'],
                )
            ));
            if ($warn != '新增成功') {
                return L('finance.table.lsxzsb');
            }
        }
        return true;
    }

    /**
     * 记录账户流水
     */
    public static function record_ac(string $acid, string $direction, float $money, string $text = '', string $type = '普通', $targetName = '', $targetDate = '', $orderNo = '', $hiddenText = null): bool|string
    {
        return self::record_execute([
            'acid' => $acid,
            'direction' => $direction,
            'money' => $money,
            'text' => $text,
            'type' => $type,
            'targetName' => $targetName,
            'targetDate' => $targetDate,
            'orderNo' => $orderNo,
            'hiddenText' => $hiddenText
        ]);
    }

    /**
     * 获取账户余额
     * @param  $acid
     * @return float
     */
    public static function money($acid): float
    {
        return find(array('table' => self::table . "_record", 'where' => "acid = '$acid'", 'sum' => "money"));
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('finance.table.account_del_title');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm,bankForm';
                $power = $this->post('type')=='现金'?self::page:'accountBank';
                break;
        }
        if (!$this->power(self::page, $act) && !$this->power('accountBank', $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power($this->post('power'), "del")) {
            $json['warn'] = L('finance.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('finance.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (static::total(array('table' => self::table . '_record', 'where' => "acid = '$info[id]' and type !='初始余额'")) > 0) {
                    $warn = L('finance.table.account_del_failed');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table . "_record", "where" => " acid = '$id' "));
                    //返回
                    $warn = L('finance.table.sccg');
                    $x++;
                }
                $text .= str_replace(['{{name}}', '{{orderNo}}'], [$info['name'], $info['orderNo']], L('finance.table.account_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.account_del_log')) . "<br>" . $text;
            $this->logText(array("type" => $this->post('power'), "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('finance.table.account_del_msg'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

